<template>
  <div class="farmer-trade-container agri-page-container">
    <div class="page-header agri-page-header">
      <div class="page-title agri-page-title">
        <el-icon><Goods /></el-icon>
        <span>交易中心</span>
      </div>
    </div>

   

    <!-- 添加/编辑农产品对话框 -->
    <el-dialog
      v-model="productDialogVisible"
      :title="isEdit ? '编辑农产品' : '发布新农产品'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="农产品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入农产品名称" />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="productForm.price"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入价格"
          />
        </el-form-item>

        <el-form-item label="单位" prop="unit">
          <el-input v-model="productForm.unit" placeholder="请输入单位，如: kg, 箱, 个" />
        </el-form-item>

        <el-form-item label="库存数量" prop="stock">
          <el-input-number
            v-model="productForm.stock"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入库存数量"
          />
        </el-form-item>

        <el-form-item label="产品图片" prop="image">
          <el-upload
            class="product-image-uploader"
            action="/api/product/upload/image"
            :headers="getUploadHeaders()"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :on-success="handleImageSuccess"
            :on-error="handleImageError"
            :on-remove="handleImageRemove"
          >
            <img v-if="productForm.image" :src="formatImageUrl(productForm.image)" class="product-image" />
            <el-icon v-else class="product-image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">点击上传产品图片，只能上传jpg/png文件，且不超过2MB</div>
        </el-form-item>

        <el-form-item label="上架状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio :label="1">立即上架</el-radio>
            <el-radio :label="0">暂不上架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="产品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入产品描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProduct" :loading="productSubmitLoading">
            {{ isEdit ? '更新' : '发布' }}
          </el-button>
        </span>
      </template>
    </el-dialog> <el-tabs v-model="activeTab" class="trade-tabs">
      <el-tab-pane label="农产品发布" name="products">
        <div class="tab-content-wrapper">
          <el-card v-loading="loading.products" class="agri-card">
            <template #header>
              <div class="card-header">
                <div class="card-title">我的农产品</div>
                <div class="card-actions">
                  <el-button type="primary" @click="handleAddProduct">
                    <el-icon><Plus /></el-icon> 发布新农产品
                  </el-button>
                </div>
              </div>
            </template>

            <div v-if="products.length === 0" class="empty-data">
              <el-empty description="暂无农产品" />
            </div>

            <div v-else class="product-list">
              <el-row :gutter="20">
                <el-col v-for="product in products" :key="product.id"
                        :xs="24" :sm="12" :md="8" :lg="6">
                  <el-card class="product-card agri-card" :body-style="{ padding: '0px' }">
                    <img
                      :src="formatImageUrl(product.image)"
                      class="product-image"
                      alt="产品图片"
                    />
                    <div class="product-info">
                      <h3 class="product-title">{{ product.name }}</h3>
                      <div class="product-meta">
                        <el-tag size="small">{{ product.category }}</el-tag>
                        <span class="product-price">¥{{ product.price }}/{{ product.unit }}</span>
                      </div>
                      <div class="product-stock">
                        库存: {{ product.stock }} {{ product.unit }}
                      </div>
                      <div class="product-status">
                        <el-tag type="success" v-if="Number(product.status) === 1">销售中</el-tag>
                        <el-tag type="info" v-else>已下架</el-tag>
                      </div>
                      <div class="product-actions">
                        <el-button type="primary" size="small" @click="handleEditProduct(product)">
                          编辑
                        </el-button>
                        <el-button
                          :type="Number(product.status) === 1 ? 'warning' : 'success'"
                          size="small"
                          @click="handleToggleProductStatus(product)"
                        >
                          {{ Number(product.status) === 1 ? '下架' : '上架' }}
                        </el-button>
                        <el-button
                          type="danger"
                          size="small"
                          @click="handleDeleteProduct(product)"
                          v-if="Number(product.status) !== 'sold'"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="订单管理" name="orders">
        <div class="tab-content-wrapper">
          <el-card v-loading="loading.orders" class="agri-card">
            <template #header>
              <div class="card-header">
                <div class="card-title">订单管理</div>
                <div class="card-actions">
                  <el-select v-model="orderFilter" placeholder="订单状态" class="filter-select">
                    <el-option label="全部订单" value="all" />
                    <el-option label="待付款" value="pending" />
                    <el-option label="待发货" value="paid" />
                    <el-option label="待收货" value="shipped" />
                    <el-option label="已完成" value="completed" />
                    <el-option label="已取消" value="cancelled" />
                  </el-select>
                </div>
              </div>
            </template>

            <!-- 订单类型选项卡 -->
            <el-tabs v-model="activeOrderTab" @tab-click="handleOrderTabChange">
              <el-tab-pane label="农产品订单" name="product">
                <!-- 确保每个tab-pane有内容 -->
                <div class="tab-content-wrapper"></div>
              </el-tab-pane>
              <el-tab-pane label="肥料订单" name="fertilizer">
                <!-- 确保每个tab-pane有内容 -->
                <div class="tab-content-wrapper"></div>
              </el-tab-pane>
            </el-tabs>

            <div v-if="filteredOrders.length === 0" class="empty-data">
              <el-empty description="暂无订单" />
            </div>

            <div v-else class="order-list">
              <div class="agri-table-wrapper">
                <el-table :data="filteredOrders" border stripe>
                  <el-table-column label="订单编号" prop="orderNo" min-width="180" />

                  <!-- 根据订单类型显示不同的列 -->
                  <template v-if="activeOrderTab === 'product'">
                    <!-- 农产品订单显示买家信息 -->
                    <el-table-column label="买家" prop="buyerName" min-width="120" />
                  </template>
                  <template v-else>
                    <!-- 肥料订单显示卖家信息 -->
                    <el-table-column label="卖家" prop="sellerName" min-width="120" />
                  </template>

                  <el-table-column label="产品" prop="productName" min-width="150" />
                  <el-table-column label="数量" min-width="80">
                    <template #default="scope">
                      {{ scope.row.quantity }} {{ scope.row.unit || '个' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="总金额" min-width="100">
                    <template #default="scope">
                      ¥{{ scope.row.totalAmount }}
                    </template>
                  </el-table-column>
                  <el-table-column label="订单日期" min-width="120">
                    <template #default="scope">
                      {{ formatDate(scope.row.orderTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="状态" min-width="100">
                    <template #default="scope">
                      <el-tag :type="getOrderStatusType(scope.row.status)">
                        {{ getOrderStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200">
                    <template #default="scope">
                      <div class="agri-operations">
                        <!-- 农产品订单操作 -->
                        <template v-if="!scope.row.isFertilizerOrder">
                          <el-button
                            v-if="scope.row.status === 'paid'"
                            type="primary"
                            size="small"
                            @click="handleShipOrder(scope.row)"
                          >
                            发货
                          </el-button>
                        </template>

                        <!-- 肥料订单操作 -->
                        <template v-else>
                          <el-button
                            v-if="scope.row.status === 'shipped'"
                            type="success"
                            size="small"
                            @click="confirmReceiveOrder(scope.row)"
                          >
                            确认收货
                          </el-button>
                        </template>

                        <el-button
                          type="info"
                          size="small"
                          @click="viewOrderDetail(scope.row)"
                        >
                          详情
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="交易记录" name="transactions">
        <div class="tab-content-wrapper">
          <el-card v-loading="loading.transactions" class="agri-card">
            <template #header>
              <div class="card-header">
                <div class="card-title">交易记录</div>
                <div class="card-actions">
                  <el-date-picker
                    v-model="transactionDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    class="date-range-picker"
                  />
                </div>
              </div>
            </template>

            <div v-if="filteredTransactions.length === 0" class="empty-data">
              <el-empty description="暂无交易记录" />
            </div>

            <div v-else class="transaction-list">
              <div class="agri-table-wrapper">
                <el-table :data="filteredTransactions" border stripe>
                  <el-table-column label="交易日期" min-width="120">
                    <template #default="scope">
                      {{ formatDate(scope.row.transactionDate) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="交易类型" min-width="100">
                    <template #default="scope">
                      <el-tag :type="getTransactionTypeTag(scope.row.type)">
                        {{ getTransactionTypeText(scope.row.type) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="订单编号" prop="orderNumber" min-width="180" />
                  <el-table-column label="产品名称" prop="productName" min-width="150" />
                  <el-table-column label="数量" min-width="80">
                    <template #default="scope">
                      {{ scope.row.quantity }} {{ scope.row.unit }}
                    </template>
                  </el-table-column>
                  <el-table-column label="金额" min-width="100">
                    <template #default="scope">
                      <span :class="{ 'income': scope.row.type === 'income', 'expense': scope.row.type === 'expense' }">
                        {{ scope.row.type === 'income' ? '+' : '-' }} ¥{{ scope.row.amount }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" prop="note" min-width="200" />
                </el-table>
              </div>

              <!-- 交易统计 -->
              <div class="transaction-stats">
                <div class="stat-item">
                  <span class="stat-label">总收入:</span>
                  <span class="stat-value income">¥{{ totalIncome }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">总支出:</span>
                  <span class="stat-value expense">¥{{ totalExpense }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">净收入:</span>
                  <span class="stat-value" :class="{ 'income': netIncome > 0, 'expense': netIncome < 0 }">
                    ¥{{ netIncome }}
                  </span>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="肥料采购" name="fertilizer">
        <div class="tab-content-wrapper">
          <el-card v-loading="loading.fertilizer" class="agri-card">
            <template #header>
              <div class="card-header">
                <div class="card-title">肥料采购</div>
                <div class="card-actions fertilizer-search-actions">
                  <el-input
                    v-model="fertilizerSearch"
                    placeholder="搜索肥料产品"
                    clearable
                    @input="handleFertilizerSearch"
                    class="fertilizer-search-input"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>

                  <el-select
                    v-model="fertilizerFilter.category"
                    placeholder="肥料类型"
                    clearable
                    @change="handleFertilizerFilter"
                    class="fertilizer-filter-select"
                  >
                    <el-option label="全部类型" value="" />
                    <el-option label="氮肥" value="nitrogen" />
                    <el-option label="磷肥" value="phosphate" />
                    <el-option label="钾肥" value="potassium" />
                    <el-option label="复合肥" value="compound" />
                    <el-option label="有机肥" value="organic" />
                    <el-option label="微生物肥料" value="microbial" />
                    <el-option label="叶面肥" value="foliar" />
                  </el-select>

                  <el-select
                    v-model="fertilizerFilter.suitableCrop"
                    placeholder="适用作物"
                    clearable
                    @change="handleFertilizerFilter"
                    class="fertilizer-filter-select"
                  >
                    <el-option label="全部作物" value="" />
                    <el-option label="水稻" value="rice" />
                    <el-option label="小麦" value="wheat" />
                    <el-option label="玉米" value="corn" />
                    <el-option label="蔬菜" value="vegetable" />
                    <el-option label="果树" value="fruit_tree" />
                  </el-select>
                </div>
              </div>
            </template>

            <div v-if="fertilizers.length === 0" class="empty-data">
              <el-empty description="暂无肥料产品" />
            </div>

            <div v-else class="fertilizer-list">
              <el-row :gutter="20">
                <el-col
                  v-for="fertilizer in filteredFertilizers"
                  :key="fertilizer.id"
                  :xs="24" :sm="12" :md="8" :lg="6"
                >
                  <el-card class="fertilizer-card agri-card" shadow="hover">
                    <div class="fertilizer-image-container">
                      <img
                        :src="formatImageUrl(fertilizer.image)"
                        class="fertilizer-image"
                        alt="肥料图片"
                      />
                    </div>
                    <div class="fertilizer-info">
                      <h3 class="fertilizer-name">{{ fertilizer.name }}</h3>
                      <div class="fertilizer-category">
                        <el-tag size="small">{{ getCategoryName(fertilizer.category) }}</el-tag>
                      </div>
                      <div class="fertilizer-meta">
                        <span class="fertilizer-nutrient">养分: {{ fertilizer.nutrientContent }}</span>
                      </div>
                      <div class="fertilizer-price">
                        ¥{{ fertilizer.price }} / {{ fertilizer.unit }}
                      </div>
                      <div class="fertilizer-crops">
                        适用:
                        <el-tag
                          v-for="crop in parseSuitableCrops(fertilizer.suitableCrops)?.slice(0, 2)"
                          :key="crop"
                          size="small"
                          type="success"
                          class="crop-tag"
                        >
                          {{ getCropName(crop) }}
                        </el-tag>
                        <span v-if="parseSuitableCrops(fertilizer.suitableCrops)?.length > 2">等</span>
                      </div>
                      <div class="fertilizer-actions">
                        <el-button type="primary" size="small" @click="viewFertilizerDetail(fertilizer)">
                          详情
                        </el-button>
                        <el-button type="success" size="small" @click="handlePurchase(fertilizer)">
                          购买
                        </el-button>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDialogVisible"
      title="订单详情"
      width="700px"
    >
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="下单日期">{{ formatDate(currentOrder.orderDate) }}</el-descriptions-item>
          <el-descriptions-item label="买家名称">{{ currentOrder.buyerName }}</el-descriptions-item>
          <el-descriptions-item label="联系方式">{{ currentOrder.buyerPhone }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{ currentOrder.productName }}</el-descriptions-item>
          <el-descriptions-item label="产品数量">{{ currentOrder.quantity }} {{ currentOrder.unit }}</el-descriptions-item>
          <el-descriptions-item label="单价">¥{{ currentOrder.price }}/{{ currentOrder.unit }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getOrderStatusType(currentOrder.status)">
              {{ getOrderStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.address }}</el-descriptions-item>
          <el-descriptions-item label="买家留言" :span="2">{{ currentOrder.note || '无' }}</el-descriptions-item>
        </el-descriptions>

        <div v-if="currentOrder.status === 'pending'" class="order-actions">
          <el-button type="success" @click="handleShipOrder(currentOrder)">发货</el-button>
          <el-button type="danger" @click="handleCancelOrder(currentOrder)">取消订单</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="发货信息"
      width="500px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-select v-model="shipForm.logisticsCompany" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="顺丰速运" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通速递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
            <el-option label="申通快递" value="STO" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="物流单号" prop="trackingNumber">
          <el-input v-model="shipForm.trackingNumber" placeholder="请输入物流单号" />
        </el-form-item>

        <el-form-item label="备注" prop="note">
          <el-input
            v-model="shipForm.note"
            type="textarea"
            :rows="2"
            placeholder="物流备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShipOrder" :loading="shipSubmitLoading">
            确认发货
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 肥料详情对话框 -->
    <el-dialog
      v-model="fertilizerDetailVisible"
      title="肥料详情"
      width="700px"
      destroy-on-close
    >
      <div v-if="currentFertilizer" class="fertilizer-detail">
        <div class="fertilizer-detail-header">
          <div class="fertilizer-detail-image">
            <img
              :src="formatImageUrl(currentFertilizer.image)"
              alt="肥料图片"
            />
          </div>
          <div class="fertilizer-detail-info">
            <h2 class="fertilizer-detail-name">{{ currentFertilizer.name }}</h2>
            <div class="fertilizer-detail-meta">
              <el-tag size="small">{{ getCategoryName(currentFertilizer.category) }}</el-tag>
              <span class="fertilizer-detail-seller">销售商: {{ currentFertilizer.seller?.name || '未知' }}</span>
            </div>
            <div class="fertilizer-detail-price">
              ¥<span class="price-value">{{ currentFertilizer.price }}</span> / {{ currentFertilizer.unit }}
            </div>
            <div class="fertilizer-detail-stock">
              库存: {{ currentFertilizer.stock }} {{ currentFertilizer.unit }}
            </div>
            <div class="fertilizer-detail-buttons">
              <el-button type="primary" @click="handlePurchase(currentFertilizer)">
                立即购买
              </el-button>
            </div>
          </div>
        </div>

        <el-divider />

        <div class="fertilizer-detail-content">
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="肥料分类">
              {{ getCategoryName(currentFertilizer.category) }}
            </el-descriptions-item>
            <el-descriptions-item label="养分含量">
              {{ currentFertilizer.nutrientContent }}
            </el-descriptions-item>
            <el-descriptions-item label="产地">
              {{ currentFertilizer.origin || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="生产日期">
              {{ currentFertilizer.productionDate || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="保质期">
              {{ currentFertilizer.shelfLife || '未知' }} 天
            </el-descriptions-item>
            <el-descriptions-item label="认证">
              <el-tag
                v-for="cert in parseCertificates(currentFertilizer.certificates)"
                :key="cert"
                size="small"
                class="cert-tag"
              >
                {{ getCertName(cert) }}
              </el-tag>
              <span v-if="!currentFertilizer.certificates || currentFertilizer.certificates.length === 0">
                无认证信息
              </span>
            </el-descriptions-item>
          </el-descriptions>

          <h3 class="section-title">适用作物</h3>
          <div class="crop-list">
            <el-tag
              v-for="crop in parseSuitableCrops(currentFertilizer.suitableCrops)"
              :key="crop"
              size="large"
              type="success"
              class="crop-tag"
            >
              {{ getCropName(crop) }}
            </el-tag>
            <span v-if="!currentFertilizer.suitableCrops || currentFertilizer.suitableCrops.length === 0">
              无数据
            </span>
          </div>

          <h3 class="section-title">使用说明</h3>
          <div class="fertilizer-instructions">
            {{ currentFertilizer.instructions || '暂无使用说明' }}
          </div>

          <h3 class="section-title">产品描述</h3>
          <div class="fertilizer-description">
            {{ currentFertilizer.description || '暂无产品描述' }}
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 肥料购买对话框 -->
    <el-dialog
      v-model="fertilizerPurchaseVisible"
      title="购买肥料"
      width="550px"
      destroy-on-close
    >
      <div class="purchase-product-info" v-if="currentFertilizer">
        <div class="purchase-product-header">
          <img
            :src="formatImageUrl(currentFertilizer.image)"
            class="purchase-product-image"
            alt="肥料图片"
          />
          <div class="purchase-product-details">
            <h3 class="purchase-product-name">{{ currentFertilizer.name }}</h3>
            <div class="purchase-product-price">
              ¥<span class="price-value">{{ currentFertilizer.price }}</span> / {{ currentFertilizer.unit }}
            </div>
          </div>
        </div>

        <el-form
          ref="purchaseFormRef"
          :model="purchaseForm"
          :rules="purchaseRules"
          label-width="100px"
          class="purchase-form"
        >
          <el-form-item label="购买数量" prop="quantity">
            <el-input-number
              v-model="purchaseForm.quantity"
              :min="1"
              :max="currentFertilizer.stock"
              :step="1"
              @change="calculateTotal"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="收货地址" prop="address">
            <el-input
              v-model="purchaseForm.address"
              type="textarea"
              :rows="2"
              placeholder="请输入详细地址"
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="purchaseForm.phone" placeholder="请输入联系电话" />
          </el-form-item>

          <el-form-item label="配送方式" prop="deliveryMethod">
            <el-radio-group v-model="purchaseForm.deliveryMethod">
              <el-radio label="express">快递配送</el-radio>
              <el-radio label="self">自提</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="支付方式" prop="paymentMethod">
            <el-radio-group v-model="purchaseForm.paymentMethod">
              <el-radio label="online">在线支付</el-radio>
              <el-radio label="cod">货到付款</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="备注" prop="note">
            <el-input
              v-model="purchaseForm.note"
              type="textarea"
              :rows="3"
              placeholder="备注信息（选填）"
            />
          </el-form-item>
        </el-form>

        <div class="purchase-summary">
          <div class="summary-item">
            <span class="summary-label">商品金额:</span>
            <span class="summary-value">¥{{ productTotal }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">运费:</span>
            <span class="summary-value">¥{{ shippingFee }}</span>
          </div>
          <div class="summary-item total">
            <span class="summary-label">总计:</span>
            <span class="summary-value">¥{{ orderTotal }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="fertilizerPurchaseVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPurchase" :loading="submitting">
            确认购买
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加支付对话框 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="订单支付"
      width="500px"
      destroy-on-close
    >
      <div v-if="currentOrder" class="payment-dialog-content">
        <div class="payment-order-info">
          <h3>订单信息</h3>
          <div class="payment-order-item">
            <span class="label">订单编号:</span>
            <span class="value">{{ currentOrder.orderNo }}</span>
          </div>
          <div class="payment-order-item">
            <span class="label">商品名称:</span>
            <span class="value">{{ currentOrder.productName }}</span>
          </div>
          <div class="payment-order-item">
            <span class="label">订单金额:</span>
            <span class="value price">¥{{ currentOrder.totalAmount }}</span>
          </div>
        </div>

        <div class="payment-method-section">
          <h3>支付方式</h3>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="unionpay">银联支付</el-radio>
          </el-radio-group>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment" :loading="paymentLoading">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailVisible"
      title="订单详情"
      width="700px"
      destroy-on-close
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="order-header">
          <div class="order-number">订单编号：{{ currentOrder.orderNo }}</div>
          <el-tag :type="getOrderStatusType(currentOrder.status)" class="order-status">
            {{ getOrderStatusText(currentOrder.status) }}
          </el-tag>
        </div>

        <el-divider />

        <div class="order-info">
          <div class="info-section">
            <h4>基本信息</h4>
            <div class="info-item">
              <span class="label">订单类型：</span>
              <span class="value">{{ currentOrder.isFertilizerOrder ? '肥料订单' : '农产品订单' }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ formatDate(currentOrder.orderTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">{{ currentOrder.isFertilizerOrder ? '卖家' : '买家' }}：</span>
              <span class="value">{{ currentOrder.isFertilizerOrder ? currentOrder.sellerName : currentOrder.buyerName }}</span>
            </div>
          </div>

          <div class="info-section">
            <h4>商品信息</h4>
            <div class="product-info">
              <div class="product-details">
                <div class="product-name">{{ currentOrder.productName }}</div>
                <div class="product-price">¥{{ currentOrder.price }} × {{ currentOrder.quantity }}{{ currentOrder.unit || '个' }}</div>
                <div class="product-total">总计：<span class="price">¥{{ currentOrder.totalAmount }}</span></div>
              </div>
            </div>
          </div>

          <div class="info-section" v-if="currentOrder.address">
            <h4>收货信息</h4>
            <div class="info-item">
              <span class="label">收货人：</span>
              <span class="value">{{ currentOrder.contactName }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ currentOrder.contactPhone }}</span>
            </div>
            <div class="info-item">
              <span class="label">收货地址：</span>
              <span class="value">{{ currentOrder.address }}</span>
            </div>
          </div>

          <div class="info-section" v-if="currentOrder.shipTime">
            <h4>物流信息</h4>
            <div class="info-item">
              <span class="label">发货时间：</span>
              <span class="value">{{ formatDate(currentOrder.shipTime) }}</span>
            </div>
          </div>
        </div>

        <div class="order-actions" v-if="currentOrder.isFertilizerOrder && currentOrder.status === 'shipped'">
          <el-button type="success" @click="confirmReceiveOrder(currentOrder)">确认收货</el-button>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDetailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Goods, Plus, Upload, Search } from '@element-plus/icons-vue';
import { useFarmerStore } from '../../store';
import { useUserStore } from '../../store';
import { format } from 'date-fns';

// 状态管理
const farmerStore = useFarmerStore();
const userStore = useUserStore();

// 默认图片
const defaultProductImage = 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png';

// Tab控制
const activeTab = ref('products');

// 数据加载状态
const loading = reactive({
  products: false,
  orders: false,
  transactions: false,
  fertilizer: false
});

// 数据列表
const products = ref([]);
const orders = ref([]);
const transactions = ref([]);
const fertilizers = ref([]);

// 交易统计变量
const incomeTotal = ref(0);
const expenseTotal = ref(0);
const balance = ref(0);

// 过滤器
const orderFilter = ref('all');
const transactionDateRange = ref([]);
const fertilizerSearch = ref('');
const fertilizerFilter = reactive({
  category: '',
  suitableCrop: ''
});

// 对话框控制
const productDialogVisible = ref(false);
const orderDialogVisible = ref(false);
const shipDialogVisible = ref(false);
const fertilizerDetailVisible = ref(false);
const fertilizerPurchaseVisible = ref(false);
const productSubmitLoading = ref(false);
const shipSubmitLoading = ref(false);
const submitting = ref(false);
const isEdit = ref(false);
const currentOrder = ref(null);
const currentProductId = ref(null);
const currentFertilizer = ref(null);

// 表单引用
const productFormRef = ref(null);
const shipFormRef = ref(null);
const purchaseFormRef = ref(null);

// 产品分类
const categories = [
  { value: '粮食', label: '粮食' },
  { value: '蔬菜', label: '蔬菜' },
  { value: '水果', label: '水果' },
  { value: '肉类', label: '肉类' },
  { value: '禽蛋', label: '禽蛋' },
  { value: '水产', label: '水产' },
  { value: '其他', label: '其他' }
];

// 产品表单
const productForm = reactive({
  id: '',
  name: '',
  category: '',
  price: 0,
  unit: '',
  stock: 0,
  image: '',
  status: 1,  // 确保使用数字类型
  description: ''
});

// 发货表单
const shipForm = reactive({
  logisticsCompany: '',
  trackingNumber: '',
  note: ''
});

// 购买表单
const purchaseForm = reactive({
  quantity: 1,
  address: '',
  phone: '',
  deliveryMethod: 'express',
  paymentMethod: 'online',
  note: ''
});

// 表单验证规则
const productRules = {
  name: [
    { required: true, message: '请输入农产品名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于0', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择上架状态', trigger: 'change' }
  ]
};

const shipRules = {
  logisticsCompany: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNumber: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
};

const purchaseRules = {
  quantity: [
    { required: true, message: '请输入购买数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '购买数量必须大于0', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度在5到100个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
};

// 添加订单类型选项卡状态
const activeOrderTab = ref('product'); // 默认显示农产品订单

// 过滤后的订单列表
const filteredOrders = computed(() => {
  // 先按订单类型分类
  const productOrders = orders.value.filter(order => !order.isFertilizerOrder);
  const fertilizerOrders = orders.value.filter(order => order.isFertilizerOrder);

  // 根据订单类型和状态过滤
  if (orderFilter.value === 'all') {
    // 根据当前选项卡返回对应类型的所有订单
    return activeOrderTab.value === 'product' ? productOrders : fertilizerOrders;
  } else {
    // 根据当前选项卡和状态过滤
    return (activeOrderTab.value === 'product' ? productOrders : fertilizerOrders)
      .filter(order => order.status === orderFilter.value);
  }
});

// 获取订单状态类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 'pending': return 'info';
    case 'paid': return 'warning';
    case 'shipped': return 'primary';
    case 'completed': return 'success';
    case 'cancelled': return 'danger';
    default: return 'info';
  }
};

// 获取订单状态文本
const getOrderStatusText = (status) => {
  switch (status) {
    case 'pending': return '待付款';
    case 'paid': return '待发货';
    case 'shipped': return '待收货';
    case 'completed': return '已完成';
    case 'cancelled': return '已取消';
    default: return '未知状态';
  }
};

// 获取交易类型标签
const getTransactionTypeTag = (type) => {
  return type === 'income' ? 'success' : 'danger';
};

// 获取交易类型文本
const getTransactionTypeText = (type) => {
  return type === 'income' ? '收入' : '支出';
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  return format(new Date(date), 'yyyy-MM-dd HH:mm');
};

// 处理添加产品
const handleAddProduct = () => {
  isEdit.value = false;

  // 重置表单值
  productForm.id = '';
  productForm.name = '';
  productForm.category = '';
  productForm.price = 0;
  productForm.unit = '';
  productForm.stock = 0;
  productForm.image = '';
  productForm.status = 1;  // 确保使用数字类型
  productForm.description = '';

  // 重置表单验证
  if (productFormRef.value) {
    productFormRef.value.resetFields();
  }

  productDialogVisible.value = true;
};

// 处理编辑产品
const handleEditProduct = (product) => {
  isEdit.value = true;
  productForm.id = product.id;
  productForm.name = product.name;
  productForm.category = product.type || product.category;
  productForm.price = Number(product.price);
  productForm.unit = product.unit;
  productForm.stock = Number(product.stock);
  productForm.description = product.description || '';
  productForm.image = product.image || '';
  productForm.status = Number(product.status);

  console.log('编辑产品，表单数据:', JSON.stringify(productForm));
  productDialogVisible.value = true;
};

// 处理删除产品
const handleDeleteProduct = (product) => {
  ElMessageBox.confirm(
    '确定要删除这个产品吗？此操作不可撤销。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await farmerStore.deleteProduct(product.id);
      console.log('删除产品结果:', res);
      ElMessage.success('删除成功');
      fetchProducts();
    } catch (error) {
      console.error('删除产品失败', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 处理上架/下架产品
const handleToggleProductStatus = async (product) => {
  try {
    let res;
    console.log('切换前的产品状态:', product.status, typeof product.status);
    
    // 确保使用一致的方式判断状态
    const currentStatus = Number(product.status);
    
    if (currentStatus === 1) {
      // 下架产品
      res = await farmerStore.unpublishProduct(product.id);
      console.log('下架产品结果:', res);
      if (res && res.success) {
        ElMessage.success('产品下架成功');
        
        // 重新获取产品列表而不是本地更新状态
        // 这样能确保状态值与后端一致
        await fetchProducts();
      } else {
        ElMessage.error(res?.message || '下架失败');
      }
    } else {
      // 上架产品
      res = await farmerStore.publishProduct(product.id);
      console.log('上架产品结果:', res);
      if (res && res.success) {
        ElMessage.success('产品上架成功');
        
        // 重新获取产品列表而不是本地更新状态
        // 这样能确保状态值与后端一致
        await fetchProducts();
      } else {
        ElMessage.error(res?.message || '上架失败');
      }
    }
  } catch (error) {
    console.error('更改产品状态失败', error);
    ElMessage.error('操作失败：' + (error.message || '未知错误'));
  }
};

// 提交产品表单
const submitProduct = async () => {
  if (!productFormRef.value) return;

  await productFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      productSubmitLoading.value = true;

      // 准备提交数据
      const formData = {
        name: productForm.name,
        type: productForm.category,
        price: parseFloat(productForm.price),
        unit: productForm.unit,
        stock: parseFloat(productForm.stock),
        description: productForm.description,
        image: productForm.image,
        status: Number(productForm.status)  // 确保转换为数字
      };

      console.log('提交产品数据:', formData);

      let res;
      if (isEdit.value) {
        // 编辑产品
        formData.id = productForm.id;
        res = await farmerStore.updateProduct(formData);
        console.log('更新产品结果:', res);
        if (res.success) {
          ElMessage.success('产品更新成功');
          productDialogVisible.value = false;
          await fetchProducts(); // 等待数据刷新完成
        } else {
          ElMessage.error(res.message || '更新失败');
        }
      } else {
        // 添加新产品
        res = await farmerStore.addProduct(formData);
        console.log('添加产品结果:', res);
        if (res.success) {
          ElMessage.success('产品添加成功');
          productDialogVisible.value = false;
          await fetchProducts(); // 等待数据刷新完成
        } else {
          ElMessage.error(res.message || '添加失败');
        }
      }
    } catch (error) {
      console.error('提交产品表单失败', error);
      ElMessage.error('提交失败：' + (error.message || '未知错误'));
    } finally {
      productSubmitLoading.value = false;
    }
  });
};

// 获取上传需要的headers
const getUploadHeaders = () => {
  const token = localStorage.getItem('token');
  return {
    Authorization: token ? `Bearer ${token}` : ''
  };
};

// 上传图片前的处理
const beforeImageUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error('图片只能是JPG或PNG格式!');
    return false;
  }

  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }

  return true;
};

// 处理图片上传成功
const handleImageSuccess = (res) => {
  console.log('图片上传成功:', res);
  if (res.success && res.data) {
    // 保存图片URL
    productForm.image = res.data;
    console.log('设置产品图片URL:', res.data);
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败: ' + (res.message || '未知错误'));
  }
};

// 处理图片URL，直接返回带token的URL
const formatImageUrl = (url) => {
  if (!url) return defaultProductImage;

  // 检查是否是后端返回的相对URL
  if (url.startsWith('/file/') || url.startsWith('/api/file/')) {
    const token = localStorage.getItem('token');
    // 确保URL以/api开头
    const apiUrl = url.startsWith('/api') ? url : `/api${url}`;

    if (token) {
      // 返回带token的URL
      return `${apiUrl}?token=${encodeURIComponent(token)}`;
    }
    return apiUrl;
  }

  return url;
};

// 获取农产品列表
const fetchProducts = async () => {
  loading.products = true;
  try {
    const productsData = await farmerStore.fetchProducts();
    console.log('获取农产品原始结果:', productsData);
    
    // 确保每个产品的status是数字类型
    const processedProducts = productsData.map(product => {
      const status = Number(product.status);
      console.log(`产品 ${product.id} (${product.name}) 状态: ${product.status} -> ${status}, 类型: ${typeof status}`);
      return {
        ...product,
        status: status // 确保统一为数字类型
      };
    });
    
    products.value = processedProducts;
    console.log('处理后的产品列表:', processedProducts);
  } catch (error) {
    console.error('获取农产品失败', error);
    ElMessage.error('获取农产品列表失败');
  } finally {
    loading.products = false;
  }
};

// 获取订单列表
const fetchOrders = async () => {
  loading.orders = true;
  try {
    const ordersData = await farmerStore.fetchOrders();
    orders.value = ordersData;
  } catch (error) {
    console.error('获取订单失败', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.orders = false;
  }
};

// 获取交易记录
const fetchTransactions = async () => {
  loading.transactions = true;
  try {
    // 构建查询参数
    const params = {};
    if (transactionDateRange.value && transactionDateRange.value.length === 2) {
      params.startDate = transactionDateRange.value[0];
      params.endDate = transactionDateRange.value[1];
    }

    console.log('查询交易记录参数:', params);
    const transactionsData = await farmerStore.fetchTransactions(params);
    transactions.value = transactionsData;

    // 获取交易统计数据
    try {
      const statsData = await farmerStore.getTransactionStats();
      console.log('交易统计数据:', statsData);

      // 更新统计数据显示
      if (statsData) {
        // 确保响应包含所需字段
        incomeTotal.value = statsData.incomeTotal || 0;
        expenseTotal.value = statsData.expenseTotal || 0;
        balance.value = statsData.balance || 0;
      }
    } catch (statsError) {
      console.error('获取交易统计失败', statsError);
      // 使用默认值
      incomeTotal.value = 0;
      expenseTotal.value = 0;
      balance.value = 0;
    }
  } catch (error) {
    console.error('获取交易记录失败', error);
    ElMessage.error('获取交易记录失败');
  } finally {
    loading.transactions = false;
  }
};

// 获取肥料列表
const fetchFertilizers = async () => {
  loading.fertilizer = true;
  try {
    const fertilizersData = await farmerStore.fetchFertilizers();
    fertilizers.value = fertilizersData;
  } catch (error) {
    console.error('获取肥料列表失败', error);
    ElMessage.error('获取肥料列表失败');
  } finally {
    loading.fertilizer = false;
  }
};

// 过滤肥料列表
const filteredFertilizers = computed(() => {
  let filtered = fertilizers.value;

  if (fertilizerSearch.value) {
    filtered = filtered.filter(fertilizer =>
      fertilizer.name.toLowerCase().includes(fertilizerSearch.value.toLowerCase())
    );
  }

  if (fertilizerFilter.category) {
    filtered = filtered.filter(fertilizer =>
      fertilizer.category === fertilizerFilter.category
    );
  }

  if (fertilizerFilter.suitableCrop) {
    filtered = filtered.filter(fertilizer =>
      fertilizer.suitableCrops?.includes(fertilizerFilter.suitableCrop)
    );
  }

  return filtered;
});

// 获取肥料分类名称
const getCategoryName = (category) => {
  const categoryNames = {
    'nitrogen': '氮肥',
    'phosphate': '磷肥',
    'potassium': '钾肥',
    'compound': '复合肥',
    'organic': '有机肥',
    'microbial': '微生物肥料',
    'foliar': '叶面肥'
  };
  return categoryNames[category] || '未知分类';
};

// 获取肥料作物名称
const getCropName = (crop) => {
  // 如果已经是中文，直接返回
  if (/[\u4e00-\u9fa5]/.test(crop)) {
    return crop;
  }

  const cropNames = {
    'rice': '水稻',
    'wheat': '小麦',
    'corn': '玉米',
    'vegetable': '蔬菜',
    'fruit_tree': '果树',
    // 添加中文到中文的映射
    '水稻': '水稻',
    '小麦': '小麦',
    '玉米': '玉米',
    '蔬菜': '蔬菜',
    '果树': '果树'
  };
  return cropNames[crop] || crop || '未知作物';
};

// 处理肥料搜索
const handleFertilizerSearch = () => {
  fetchFertilizers();
};

// 处理肥料过滤
const handleFertilizerFilter = () => {
  fetchFertilizers();
};

// 计算总金额
const calculateTotal = () => {
  if (!currentFertilizer.value) return '0.00';
  return (currentFertilizer.value.price * purchaseForm.quantity).toFixed(2);
};

// 处理肥料购买
const handlePurchase = (fertilizer) => {
  currentFertilizer.value = fertilizer;

  // 重置表单
  purchaseForm.quantity = 1;
  purchaseForm.address = '';
  purchaseForm.phone = '';
  purchaseForm.deliveryMethod = 'express';
  purchaseForm.paymentMethod = 'online';
  purchaseForm.note = '';

  // 关闭详情对话框，打开购买对话框
  fertilizerDetailVisible.value = false;
  fertilizerPurchaseVisible.value = true;
};

// 处理查看肥料详情
const viewFertilizerDetail = (fertilizer) => {
  currentFertilizer.value = fertilizer;
  fertilizerDetailVisible.value = true;
};

// 支付相关变量
const orderDetailVisible = ref(false);
const paymentDialogVisible = ref(false);
const paymentMethod = ref('');
const paymentLoading = ref(false);

// 支付订单
const payOrder = (order) => {
  currentOrder.value = order;
  paymentMethod.value = '';
  paymentDialogVisible.value = true;
};

// 确认支付
const confirmPayment = async () => {
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式');
    return;
  }

  if (!currentOrder.value || !currentOrder.value.id) {
    console.error('当前订单信息不完整:', currentOrder.value);
    ElMessage.error('订单信息不完整，无法支付');
    return;
  }

  console.log('准备支付订单:', currentOrder.value.id);

  try {
    paymentLoading.value = true;

    // 调用支付API
    const result = await farmerStore.payOrder(currentOrder.value.id);

    if (result) {
      ElMessage.success('支付成功');
      paymentDialogVisible.value = false;

      // 更新订单状态
      if (currentOrder.value) {
        currentOrder.value.status = 1; // 已支付，待发货
      }

      // 刷新订单列表
      fetchOrders();
    } else {
      ElMessage.error('支付失败');
    }
  } catch (error) {
    console.error('支付失败', error);
    ElMessage.error('支付失败: ' + (error.message || '未知错误'));
  } finally {
    paymentLoading.value = false;
  }
};

// 提交肥料购买订单
const submitPurchase = async () => {
  if (!purchaseFormRef.value) return;

  await purchaseFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      submitting.value = true;

      // 准备订单数据
      const orderData = {
        productId: currentFertilizer.value.id,
        productName: currentFertilizer.value.name,
        productImage: currentFertilizer.value.image,
        quantity: purchaseForm.quantity,
        price: currentFertilizer.value.price,
        totalAmount: orderTotal.value,
        address: purchaseForm.address,
        contactPhone: purchaseForm.phone,
        contactName: userStore.userInfo?.username || '用户',
        remark: purchaseForm.note,
        sellerId: currentFertilizer.value.sellerId,
        sellerName: currentFertilizer.value.sellerName || '未知卖家',
        status: 0,  // 待付款状态
        orderType: 1  // 肥料订单类型
      };

      console.log('购买订单数据:', orderData);

      // 创建订单
      const orderResponse = await farmerStore.createOrder(orderData);
      console.log('创建订单响应:', orderResponse);
      console.log('订单响应数据结构:', JSON.stringify(orderResponse, null, 2));

      if (!orderResponse) {
        throw new Error('订单创建失败');
      }

      // 创建支出交易记录
      const transactionData = {
        type: 'expense',
        orderNumber: orderResponse.orderNo || `EXP-${Date.now()}`,
        productName: currentFertilizer.value.name,
        quantity: purchaseForm.quantity,
        unit: currentFertilizer.value.unit,
        amount: parseFloat(orderTotal.value),
        transactionDate: new Date().toISOString(),
        note: `购买${currentFertilizer.value.name}支出`
      };

      console.log('创建交易记录数据:', transactionData);

      // 调用API创建交易记录
      const transactionResponse = await farmerStore.createTransaction(transactionData);
      console.log('创建交易记录响应:', transactionResponse);

      ElMessage.success('订单创建成功，请完成支付');
      fertilizerPurchaseVisible.value = false;

      // 刷新交易记录和订单列表
      fetchTransactions();
      fetchOrders();

      // 构建订单对象，确保包含必要的ID
      const orderObj = {
        id: orderResponse.id || orderResponse.data?.id,
        orderNo: orderResponse.orderNo || orderResponse.data?.orderNo,
        productName: currentFertilizer.value.name,
        totalAmount: orderTotal.value
      };

      console.log('支付订单对象:', orderObj);

      // 显示支付对话框
      setTimeout(() => {
        currentOrder.value = orderObj;
        paymentDialogVisible.value = true;
      }, 500);
    } catch (error) {
      console.error('购买失败', error);
      ElMessage.error('购买失败: ' + (error.message || '未知错误'));
    } finally {
      submitting.value = false;
    }
  });
};

// 获取肥料认证名称
const getCertName = (cert) => {
  // 如果已经是中文，直接返回
  if (/[\u4e00-\u9fa5]/.test(cert)) {
    return cert;
  }

  const certNames = {
    'fertilizer_registration': '肥料登记证',
    'organic_fertilizer': '有机肥料认证',
    'pollution_free': '无公害肥料',
    'iso9001': '质量管理体系认证',
    'quality_test': '产品质量检测报告',
    'green_environmental': '绿色环保认证',
    // 添加中文到中文的映射
    '肥料登记证': '肥料登记证',
    '有机肥料认证': '有机肥料认证',
    '无公害肥料': '无公害肥料',
    '质量管理体系认证': '质量管理体系认证',
    '产品质量检测报告': '产品质量检测报告',
    '绿色环保认证': '绿色环保认证'
  };
  return certNames[cert] || cert;
};

// 处理图片上传失败
const handleImageError = (error) => {
  console.error('图片上传失败:', error);
  ElMessage.error('图片上传失败，请重试');
};

// 取消图片上传
const handleImageRemove = () => {
  productForm.image = '';
};

// 查看订单详情
const handleViewOrder = (order) => {
  currentOrder.value = order;
  orderDialogVisible.value = true;
};

// 处理订单发货
const handleShipOrder = (order) => {
  currentOrder.value = order;
  // 初始化发货表单
  shipForm.orderId = order.id;
  shipForm.logisticsCompany = '';
  shipForm.trackingNumber = '';
  shipForm.note = '';
  // 显示发货对话框
  shipDialogVisible.value = true;
};

// 确认发货
const confirmShipOrder = async () => {
  if (!shipFormRef.value) return;

  await shipFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写完整的发货信息');
      return;
    }

    try {
      shipSubmitLoading.value = true;

      // 准备发货数据
      const shipData = {
        orderId: currentOrder.value.id,
        logisticsCompany: shipForm.logisticsCompany,
        trackingNumber: shipForm.trackingNumber,
        note: shipForm.note
      };

      console.log('发货数据:', shipData);

      // 调用店铺 shipOrder 方法
      const result = await farmerStore.shipOrder(currentOrder.value.id, shipData);

      if (result.success) {
        ElMessage.success('订单发货成功');
        shipDialogVisible.value = false;

        // 更新当前订单状态
        if (currentOrder.value) {
          currentOrder.value.status = 'shipped';
          currentOrder.value.shipDate = new Date().toISOString();
          currentOrder.value.logistics = {
            company: shipForm.logisticsCompany,
            trackingNumber: shipForm.trackingNumber,
            note: shipForm.note
          };
        }

        // 重新获取订单列表
        await fetchOrders();

        // 强制刷新视图
        orders.value = [...orders.value];
      } else {
        ElMessage.error(result.message || '发货失败');
      }
    } catch (error) {
      console.error('发货失败', error);
      ElMessage.error('发货失败: ' + (error.message || '未知错误'));
    } finally {
      shipSubmitLoading.value = false;
    }
  });
};

// 监听日期范围变化
watch(transactionDateRange, (newRange) => {
  if (activeTab.value === 'transactions') {
    console.log('日期范围变化:', newRange);
    fetchTransactions();
  }
});

// 解析证书列表
const parseCertificates = (certificates) => {
  if (!certificates) return [];

  // 如果已经是数组，直接返回
  if (Array.isArray(certificates)) {
    return certificates;
  }

  // 如果是JSON字符串，尝试解析
  if (typeof certificates === 'string') {
    try {
      if (certificates.startsWith('[') && certificates.endsWith(']')) {
        return JSON.parse(certificates);
      } else if (certificates.includes(',')) {
        return certificates.split(',').map(item => item.trim());
      } else {
        return [certificates.trim()];
      }
    } catch (e) {
      console.error('解析证书列表失败:', e);
      return [certificates];
    }
  }

  return [];
};

// 解析适用作物列表
const parseSuitableCrops = (crops) => {
  if (!crops) return [];

  // 如果已经是数组，直接返回
  if (Array.isArray(crops)) {
    return crops;
  }

  // 如果是JSON字符串，尝试解析
  if (typeof crops === 'string') {
    try {
      if (crops.startsWith('[') && crops.endsWith(']')) {
        return JSON.parse(crops);
      } else if (crops.includes(',')) {
        return crops.split(',').map(item => item.trim());
      } else {
        return [crops.trim()];
      }
    } catch (e) {
      console.error('解析适用作物列表失败:', e);
      return [crops];
    }
  }

  return [];
};

// 处理订单类型选项卡切换
const handleOrderTabChange = (tab) => {
  console.log('切换订单类型:', tab.name);
  // 重置订单状态过滤
  orderFilter.value = 'all';
};

// 确认收货
const confirmReceiveOrder = async (order) => {
  try {
    ElMessageBox.confirm(
      `确认已收到商品"${order.productName}"吗？`,
      '确认收货',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      try {
        const result = await farmerStore.receiveOrder(order.id);
        if (result) {
          ElMessage.success('确认收货成功');
          // 刷新订单列表
          fetchOrders();
          // 关闭详情对话框
          orderDetailVisible.value = false;
        } else {
          ElMessage.error('确认收货失败');
        }
      } catch (error) {
        console.error('确认收货操作失败', error);
        ElMessage.error('确认收货失败: ' + (error.message || '未知错误'));
      }
    }).catch(() => {
      // 用户取消操作
    });
  } catch (error) {
    console.error('确认收货对话框显示失败', error);
    ElMessage.error('操作失败: ' + (error.message || '未知错误'));
  }
};

// 组件挂载时加载数据
onMounted(() => {
  // 使用setTimeout确保DOM已经完全渲染
  setTimeout(() => {
    fetchProducts();
    fetchOrders();
    fetchTransactions();
    fetchFertilizers();
  }, 0);
});

// 查看订单详情
const viewOrderDetail = (order) => {
  currentOrder.value = order;
  orderDetailVisible.value = true;
};

// 过滤后的交易记录
const filteredTransactions = computed(() => {
  if (!transactions.value || transactions.value.length === 0) {
    return [];
  }

  // 如果设置了日期范围，则按日期过滤
  if (transactionDateRange.value && transactionDateRange.value.length === 2) {
    const startDate = new Date(transactionDateRange.value[0]);
    const endDate = new Date(transactionDateRange.value[1]);
    endDate.setHours(23, 59, 59, 999); // 设置为当天结束时间

    return transactions.value.filter(transaction => {
      const transactionDate = new Date(transaction.transactionDate);
      return transactionDate >= startDate && transactionDate <= endDate;
    });
  }

  return transactions.value;
});

// 计算总收入
const totalIncome = computed(() => {
  if (!filteredTransactions.value || filteredTransactions.value.length === 0) {
    return 0;
  }

  return filteredTransactions.value
    .filter(transaction => transaction.type === 'income')
    .reduce((sum, transaction) => sum + parseFloat(transaction.amount || 0), 0)
    .toFixed(2);
});

// 计算总支出
const totalExpense = computed(() => {
  if (!filteredTransactions.value || filteredTransactions.value.length === 0) {
    return 0;
  }

  return filteredTransactions.value
    .filter(transaction => transaction.type === 'expense')
    .reduce((sum, transaction) => sum + parseFloat(transaction.amount || 0), 0)
    .toFixed(2);
});

// 计算净收入
const netIncome = computed(() => {
  return (parseFloat(totalIncome.value) - parseFloat(totalExpense.value)).toFixed(2);
});

// 计算商品总价
const productTotal = computed(() => {
  if (!currentFertilizer.value || !purchaseForm.quantity) {
    return '0.00';
  }
  return (currentFertilizer.value.price * purchaseForm.quantity).toFixed(2);
});

// 计算运费
const shippingFee = computed(() => {
  if (purchaseForm.deliveryMethod === 'self') {
    return '0.00';
  }
  return '10.00'; // 默认运费
});

// 计算订单总价
const orderTotal = computed(() => {
  return (parseFloat(productTotal.value) + parseFloat(shippingFee.value)).toFixed(2);
});
</script>



<style scoped>
.farmer-trade-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
  color: var(--primary-color);
}

.trade-tabs {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
}

.filter-select {
  width: 150px;
}

.date-range-picker {
  width: 350px;
}

/* 农产品卡片样式 */
.product-list {
  margin-bottom: 20px;
}

/* 列样式 */
.product-list .el-col,
.fertilizer-list .el-col {
  display: flex;
  margin-bottom: 20px;
}

/* 卡片容器样式 */
.product-list .el-col .el-card,
.fertilizer-list .el-col .el-card {
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: visible; /* 防止内容被截断 */
}

/* 卡片内容区样式 */
.product-list .el-col .el-card__body,
.fertilizer-list .el-col .el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: visible; /* 防止内容被截断 */
}

/* 产品卡片样式 */
.product-card {
  margin-bottom: 0; /* 移除多余的底部外边距 */
  transition: transform 0.3s;
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: visible; /* 防止内容被截断 */
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-card .product-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  display: block;
}

.product-card .product-info {
  padding: 14px;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 180px; /* 确保足够的高度容纳按钮 */
  position: relative; /* 为绝对定位提供参考 */
}

.product-card .product-title {
  margin: 0 0 10px;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-card .product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.product-card .product-price {
  color: #ff6b6b;
  font-weight: bold;
}

.product-card .product-stock {
  margin-bottom: 10px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.product-card .product-status {
  margin-bottom: 40px; /* 为底部按钮留出空间 */
}

.product-card .product-actions {
  display: flex;
  gap: 10px;
  position: absolute; /* 绝对定位按钮 */
  bottom: 14px;
  left: 14px;
  right: 14px;
}

/* 修复按钮样式 */
.product-card .product-actions .el-button {
  flex: 1;
  margin-left: 0;
  margin-right: 0;
}

/* 交易统计样式 */
.transaction-stats {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-label {
  font-weight: bold;
}

.stat-value {
  font-size: 18px;
}

.income {
  color: #67c23a;
}

.expense {
  color: #f56c6c;
}

/* 订单操作样式 */
.order-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

/* 图片上传样式 */
.product-image-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
  margin-bottom: 8px;
}

.product-image-uploader:hover {
  border-color: var(--primary-color);
}

.product-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
}

.product-image-uploader .product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 肥料卡片样式 */
.fertilizer-list {
  margin-bottom: 20px;
}

.fertilizer-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.fertilizer-card:hover {
  transform: translateY(-5px);
}

.fertilizer-image-container {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
  border-radius: 6px 6px 0 0;
}

.fertilizer-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.fertilizer-info {
  padding: 14px;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.fertilizer-name {
  margin: 0 0 10px;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.fertilizer-category {
  margin-bottom: 10px;
}

.fertilizer-meta {
  margin-bottom: 10px;
}

.fertilizer-price {
  margin-bottom: 10px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.fertilizer-crops {
  margin-bottom: 10px;
}

.fertilizer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: auto;
}

/* 肥料详情样式 */
.fertilizer-detail-header {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.fertilizer-detail-image {
  width: 200px;
  height: 200px;
  border-radius: 4px;
  overflow: hidden;
}

.fertilizer-detail-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.fertilizer-detail-info {
  flex: 1;
}

.fertilizer-detail-name {
  margin: 0 0 10px;
  font-size: 20px;
  font-weight: bold;
}

.fertilizer-detail-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.fertilizer-detail-seller {
  color: var(--el-text-color-secondary);
}

.fertilizer-detail-price {
  margin: 15px 0;
  font-size: 18px;
  color: #ff6b6b;
}

.fertilizer-detail-price .price-value {
  font-size: 24px;
  font-weight: bold;
}

.fertilizer-detail-stock {
  margin-bottom: 15px;
  color: var(--el-text-color-secondary);
}

.fertilizer-detail-buttons {
  margin-top: 20px;
}

.section-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: bold;
}

.crop-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.crop-tag {
  margin-right: 5px;
}

.cert-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.fertilizer-instructions,
.fertilizer-description {
  line-height: 1.6;
  margin-bottom: 20px;
  color: var(--el-text-color-regular);
}

/* 购买表单样式 */
.purchase-form-container {
  padding: 0 10px;
}

.purchase-product-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.purchase-product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 15px;
  object-fit: cover;
}

.purchase-product-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: bold;
}

.purchase-product-price {
  color: #ff6b6b;
}

.purchase-product-price .price-value {
  font-size: 18px;
  font-weight: bold;
}

.purchase-summary {
  margin-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.summary-item.total {
  font-weight: bold;
  font-size: 18px;
  margin-top: 10px;
  border-top: 1px dashed var(--el-border-color-lighter);
  padding-top: 10px;
}

/* 订单详情样式 */
.order-detail {
  padding: 10px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.order-number {
  font-size: 16px;
  font-weight: bold;
}

.order-status {
  font-size: 14px;
}

.info-section {
  margin-bottom: 20px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  padding: 15px;
}

.info-section h4 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
  color: var(--el-text-color-primary);
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding-bottom: 8px;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
}

.info-item .label {
  width: 100px;
  color: var(--el-text-color-secondary);
  flex-shrink: 0;
}

.info-item .value {
  flex: 1;
  font-weight: 500;
}

.order-detail .product-info {
  display: flex;
  gap: 15px;
}

.order-detail .product-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.order-detail .product-details {
  flex: 1;
}

.order-detail .product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.order-detail .product-price {
  color: var(--el-text-color-secondary);
  margin-bottom: 10px;
}

.order-detail .product-total {
  font-weight: bold;
}

.order-detail .product-total .price {
  color: #ff6b6b;
  font-size: 16px;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .filter-select,
  .date-range-picker {
    width: 100%;
    margin-top: 10px;
  }

  .transaction-stats {
    flex-direction: column;
    gap: 10px;
  }

  .fertilizer-list .el-row {
    margin-right: 0 !important;
    margin-left: 0 !important;
  }

  .fertilizer-card {
    margin-left: 0;
    margin-right: 0;
  }

  .order-detail .product-info {
    flex-direction: column;
  }

  .info-item {
    flex-direction: column;
  }

  .info-item .label {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>
